﻿using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;

namespace SelfHosting.Filters
{
    /// <summary>
    /// Attribut pour renvoyer un message un peu plus parlant en cas d'exception
    /// </summary>
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// Méthode appelée quand une exception se déclenche
        /// </summary>
        /// <param name="context">contexte</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            var ex = context.Exception;
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            string message = ex.Message;

            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(message),
            };
            throw new HttpResponseException(response);
        }
    }
}
